package com.acoffee.springcloud.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

public class JWTUtils {
    private static final String SECRET = "ETMS"; // 秘钥
    private static final String ISSUSER = "java"; // 签发人
    private static final long EXPIRES = 30*60*1000; // token的过期时间

    // 用来创建jwt静态方法
    public static String create(String uname) {
        // 指定一个加密算法
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        Date now = new Date();
        Date expires = new Date(now.getTime() + EXPIRES);
        // 创建jwt
        String jwt = JWT.create()
                .withIssuer(ISSUSER)                // 签发人
                .withIssuedAt(now)                  // 签发时间
                .withExpiresAt(expires)             // 过期时间
                .withClaim("uname", uname)    // 保存用户信息
                .sign(algorithm);                   // 加密算法
        return jwt;
    }

    // 校验jwt是否合法
    public static boolean verify(String token) {
        try {
            // 签名算法
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTVerifier verifier = JWT.require(algorithm).withIssuer(ISSUSER).build();
            verifier.verify(token);
            return true;
        } catch (Exception ex) {
            //ex.printStackTrace();
            return false;
        }
    }

    // 从token中获取用户名
    public static String getUname(String token) {
        try {
            return JWT.decode(token).getClaim("uname").asString();
        } catch (Exception ex) {
            //ex.printStackTrace();
            return "";
        }
    }

    // 判断token是否过期
    public static boolean isExpires(String token) {
        Date now = new Date();
        Date expire = JWT.decode(token).getExpiresAt();
        if (now.after(expire)) {
            return true;
        }
        return false;
    }

}
